#ifndef __TABLE_COMPONENT_HPP__
#define __TABLE_COMPONENT_HPP__

#include <string>
#include <unordered_map>
#include <vector>
#include "entt/entt.hpp"

namespace PocketSurvival
{
    struct Component;

    class TableComponent
    {
        friend class ComponentsManager;
    private:
        std::unordered_map<entt::id_type, Component *> m_componentMap;
    public:
        std::mutex tableMutex;

    public:
        template<typename T> 
        T* findComponent()
        {
            std::lock_guard<std::mutex> lk(tableMutex);
            
            entt::id_type id = entt::type_id<T*>().hash();
            auto it = m_componentMap.find(id);
            if (it != m_componentMap.end())
            {
                T *ptr = reinterpret_cast<T*>(it->second);
                return ptr;
            }
            return nullptr;
        }

        /**
         * @brief 查找所有同类型的组件
         * @note 这个很影响性能，尽量不要在 update 中使用
         */
        template<typename T> 
        void dynamicFindComponent(std::vector<T*> &outVec)
        {
            std::lock_guard<std::mutex> lk(tableMutex);

            for (auto it = m_componentMap.begin(); it != m_componentMap.end(); ++it)
            {
                T* ptr = dynamic_cast<T*>(it->second);
                if (ptr != nullptr)
                {
                    outVec.push_back(ptr);
                }
            }
        }
    };
        
} // namespace PocketSurvival

#endif
